package com.zlq.login.controller;

import com.google.code.kaptcha.Constants;
import com.zlq.login.dao.UserDaoLo;
import com.zlq.login.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(urlPatterns = "/registerController")
public class RegisterController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        UserDaoLo ud = new UserDaoLo();

        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=Utf-8");

        String token = (String) req.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
        req.getSession().removeAttribute(Constants.KAPTCHA_SESSION_KEY);

        String name = req.getParameter("name");
        String password = req.getParameter("password");
        String code = req.getParameter("code");

        if ((!name.isEmpty() || !name.equals(" ")) && (!password.isEmpty() || !password.equals(" "))&& ((code != null) || token.equals(code))) {
            req.getSession().setAttribute("name",name);
            ud.save(new User(name, password));
//            resp.sendRedirect("list.do");
            resp.sendRedirect("/static/login.jsp");
        } else {
            resp.sendRedirect("/static/register.jsp");
        }


    }
}
